from logging import Logger
from django.shortcuts import get_object_or_404
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from apps.schedule.services.ai_services import ScheduleAIService
from apps.schedule.models import Event
from apps.note.models import Note
from datetime import date

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def extract_schedules_from_note(request, note_id):
    """ 从笔记提取日程信息 """
    try:
        # 获取笔记内容
        note = get_object_or_404(Note, id=note_id, user=request.user)
        
        if not note.content or len(note.content.strip()) < 10:
            return Response({
                'success': False,
                'message': '笔记内容太短，无法提取日程信息'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 实例化AI服务
        ai_service = ScheduleAIService()
        
        # 获取当前日期信息
        now = date.today()
        current_date_info = {
            'year': now.year,
            'month': now.month,
            'day': now.day,
            'weekday': now.weekday()
        }
        
        try:
            # 使用AI服务分析笔记内容
            extracted_schedules = ai_service.analyze_content(note.content, current_date_info)
        except Exception as e:
            # AI分析失败时记录错误并返回友好提示
            import logging
            logger = logging.getLogger('apps')
            logger.error(f"AI分析笔记内容失败: {str(e)}")
            
            return Response({
                'success': False,
                'message': 'AI服务暂时不可用，请稍后再试',
                'error': str(e)
            }, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        
        if not extracted_schedules:
            return Response({
                'success': False,
                'message': '未能从笔记内容中提取到日程信息'
            }, status=status.HTTP_200_OK)
        
        # 确保所有日期使用正确的年份
        current_year = now.year
        for schedule in extracted_schedules:
            if 'date' in schedule and schedule['date']:
                try:
                    # 解析日期
                    from datetime import datetime
                    date_obj = datetime.strptime(schedule['date'], '%Y-%m-%d').date()
                    # 如果年份不是当前年份，更新为当前年份
                    if date_obj.year != current_year:
                        # 创建新的日期对象，保持月和日不变，但使用当前年份
                        new_date = date_obj.replace(year=current_year)
                        
                        # 检查日期是否已过
                        if new_date < now:
                            # 可能是明年的日期
                            new_date = new_date.replace(year=current_year + 1)
                        
                        schedule['date'] = new_date.strftime('%Y-%m-%d')
                        schedule['is_date_ai_suggested'] = True
                except (ValueError, TypeError) as e:
                    Logger.error(f"处理日期时出错: {str(e)}")
                    # 如果日期格式错误，使用当前日期
                    schedule['date'] = now.strftime('%Y-%m-%d')
                    schedule['is_date_ai_suggested'] = True
            else:
                # 如果没有日期，使用当前日期
                schedule['date'] = now.strftime('%Y-%m-%d')
                schedule['is_date_ai_suggested'] = True
        
        # 格式化返回数据，确保所有字段都有有效值
        result = {
            'events': [],
            'count': len(extracted_schedules)
        }
        
        for schedule in extracted_schedules:
            # 确保时间格式正确
            import re
            start_time = schedule.get('start_time', '09:00')
            end_time = schedule.get('end_time', '10:00')
            
            # 验证时间格式
            try:
                # 尝试解析时间，确保格式为HH:MM
                if start_time and not re.match(r'^\d{2}:\d{2}$', start_time):
                    start_time = '09:00'
                
                if end_time and not re.match(r'^\d{2}:\d{2}$', end_time):
                    end_time = '10:00'
            except Exception as e:
                start_time = '09:00'
                end_time = '10:00'
            
            # 确保标题不超过50个字符
            title = schedule.get('title', '未命名日程')
            if len(title) > 50:
                title = title[:50]
                
            # 确保描述字段使用关键点信息
            key_points = schedule.get('key_points', [])
            description = schedule.get('description', '')
            
            # 如果有关键点，直接使用关键点作为描述
            if key_points and len(key_points) > 0:
                # 使用中文顿号连接关键点
                description = '、'.join(key_points)
                
                # 确保不超过30个字符
                if len(description) > 30:
                    description = description[:27] + '...'
            elif not description and title:
                # 如果没有关键点和描述，使用标题
                description = title
            
            event = {
                'title': title,
                'description': description,
                'date': schedule.get('date', now.strftime('%Y-%m-%d')),
                'start_time': start_time,
                'end_time': end_time,
                'period': schedule.get('period', 'morning'),
                'importance': schedule.get('importance', 'medium'),
                'location': schedule.get('location', ''),
                'key_points': schedule.get('key_points', []),
                'is_date_ai_suggested': schedule.get('is_date_ai_suggested', False),
                'is_time_ai_suggested': schedule.get('is_time_ai_suggested', False),
                'is_location_ai_suggested': schedule.get('is_location_ai_suggested', False)
            }
            result['events'].append(event)
        
        # 返回提取的日程信息，但不创建
        return Response({
            'success': True,
            'message': f'成功从笔记提取了{len(result["events"])}个日程',
            'count': len(result['events']),
            'events': result['events']
        }, status=status.HTTP_200_OK)
        
    except Exception as e:
        # 记录详细错误信息
        import logging
        import traceback
        logger = logging.getLogger('apps')
        logger.error(f"从笔记提取日程失败: {str(e)}\n{traceback.format_exc()}")
        
        return Response({
            'success': False,
            'message': '处理请求时出错',
            'error': str(e)
        }, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_note_related_schedules(request, note_id):
    """获取笔记关联的日程列表"""
    try:
        note = get_object_or_404(Note, id=note_id, user=request.user)
        
        # 查询关联日程
        schedules = Event.objects.filter(
            user=request.user,
            related_note_id=note_id
        ).order_by('date', 'start_time')
        
        # 返回结果
        return Response([{
            'id': event.id,
            'title': event.title,
            'date': event.date,
            'start_time': event.start_time,
            'end_time': event.end_time,
            'location': event.location,
            'status': event.status
        } for event in schedules])
        
    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create_schedules_from_note(request, note_id):
    """确认创建从笔记提取的日程"""
    try:
        # 获取笔记
        note = get_object_or_404(Note, id=note_id, user=request.user)
        
        # 获取请求中的日程数据
        events_data = request.data.get('events', [])
        ignore_conflicts = request.data.get('ignore_conflicts', False)
        
        if not events_data:
            return Response({
                'success': False,
                'message': '没有提供日程数据'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 创建日程记录
        created_events = []
        for schedule_data in events_data:
            try:
                # 确保必要字段存在
                if not schedule_data.get('date') or not schedule_data.get('start_time'):
                    continue
                
                # 处理日期和时间格式
                from datetime import datetime, time
                import re
                
                # 处理日期 - 确保是日期对象
                date_str = schedule_data.get('date')
                if isinstance(date_str, str):
                    try:
                        # 尝试解析日期字符串 (格式: YYYY-MM-DD)
                        date_obj = datetime.strptime(date_str, '%Y-%m-%d').date()
                    except ValueError:
                        # 如果解析失败，使用当前日期
                        date_obj = datetime.now().date()
                else:
                    # 如果已经是日期对象，直接使用
                    date_obj = date_str
                
                # 处理开始时间 - 确保是时间对象
                start_time_str = schedule_data.get('start_time')
                if isinstance(start_time_str, str):
                    # 移除可能的非法字符
                    start_time_str = re.sub(r'[^0-9:]', '', start_time_str)
                    try:
                        # 尝试解析时间字符串 (格式: HH:MM)
                        start_time_obj = datetime.strptime(start_time_str, '%H:%M').time()
                    except ValueError:
                        # 如果解析失败，使用默认时间
                        start_time_obj = time(9, 0)  # 9:00 AM
                else:
                    # 如果已经是时间对象，直接使用
                    start_time_obj = start_time_str
                
                # 处理结束时间 - 确保是时间对象
                end_time_str = schedule_data.get('end_time', start_time_str)
                if isinstance(end_time_str, str):
                    # 移除可能的非法字符
                    end_time_str = re.sub(r'[^0-9:]', '', end_time_str)
                    try:
                        # 尝试解析时间字符串 (格式: HH:MM)
                        end_time_obj = datetime.strptime(end_time_str, '%H:%M').time()
                    except ValueError:
                        # 如果解析失败，使用开始时间加1小时
                        if isinstance(start_time_obj, time):
                            hour = (start_time_obj.hour + 1) % 24
                            end_time_obj = time(hour, start_time_obj.minute)
                        else:
                            end_time_obj = time(10, 0)  # 10:00 AM
                else:
                    # 如果已经是时间对象，直接使用
                    end_time_obj = end_time_str
                
                # 检查是否存在冲突（如果不忽略冲突）
                if not ignore_conflicts:
                    # 检查当天是否已有日程
                    existing_events = Event.objects.filter(
                        user=request.user,
                        date=date_obj,
                        start_time__lt=end_time_obj,
                        end_time__gt=start_time_obj
                    )
                    
                    if existing_events.exists():
                        # 如果有冲突且不忽略，则跳过此日程
                        continue
                
                # 构建日程数据
                event_data = {
                    'user': request.user,
                    'title': schedule_data.get('title', '未命名日程'),
                    'description': schedule_data.get('description', ''),
                    'date': date_obj,
                    'start_time': start_time_obj,
                    'end_time': end_time_obj,
                    'location': schedule_data.get('location', ''),
                    'importance': schedule_data.get('importance', 'medium'),
                    'related_note_id': note_id,
                    'from_note': True
                }
                
                # 创建日程
                event = Event.objects.create(**event_data)
                created_events.append(event)
            except Exception as e:
                # 单个日程创建失败时记录错误但继续处理其他日程
                import logging
                logger = logging.getLogger('apps')
                logger.error(f"创建日程失败: {str(e)}, 数据: {schedule_data}")
                continue
        
        if not created_events:
            return Response({
                'success': False,
                'message': '提取到日程信息但创建失败，请检查日程格式'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 返回结果
        return Response({
            'success': True,
            'message': f'成功从笔记创建了{len(created_events)}个日程',
            'count': len(created_events),
            'events': [{
                'id': event.id,
                'title': event.title,
                'date': event.date,
                'start_time': event.start_time,
                'end_time': event.end_time
            } for event in created_events]
        }, status=status.HTTP_201_CREATED)
        
    except Exception as e:
        # 记录详细错误信息
        import logging
        import traceback
        logger = logging.getLogger('apps')
        logger.error(f"创建日程失败: {str(e)}\n{traceback.format_exc()}")
        
        return Response({
            'success': False,
            'message': '处理请求时出错',
            'error': str(e)
        }, status=status.HTTP_400_BAD_REQUEST) 